/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sgt.supermarket;

import org.securityfilter.realm.SimpleSecurityRealmBase;
import sgt.supermarket.entity.Employee;
import sgt.supermarket.entity.Role;
import sgt.supermarket.hibernatedao.HibernateDAOFactory;

/**
 *
 * @author Administrator
 */
public class SecurityRealm extends SimpleSecurityRealmBase {

    @Override
    public boolean booleanAuthenticate(String username, String password) {
        HibernateDAOFactory factory = new HibernateDAOFactory();
        Employee employee = factory.getEmployeeDAO().getByUsername(username);
        if (employee == null) {
            return false;
        }
        return employee.isEnabled() && employee.getPassword().equals(password);
    }

    @Override
    public boolean isUserInRole(String username, String rolename) {
        HibernateDAOFactory factory = new HibernateDAOFactory();
        Employee employee = factory.getEmployeeDAO().getByUsername(username);
        if (employee == null) {
            return false;
        }
        for (Role r : employee.getRoles()) {
            if (r.getName().equals(rolename)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isUserInRoles(String username, String role1, String role2, String role3) {
        return isUserInRoles(username, role1) || isUserInRoles(username, role2) || isUserInRoles(username, role3);
    }

    public static boolean isUserInRoles(String username, String role1, String role2) {
        return isUserInRoles(username, role1) || isUserInRoles(username, role2);
    }

    public static boolean isUserInRoles(String username, String role) {
        if (username == null) {
            return false;
        }
        if (username.isEmpty()) {
            return false;
        }

        SecurityRealm realm = new SecurityRealm();
        if (realm.isUserInRole(username, role)) {
            return true;
        }
        return false;
    }
}
